import { ScrollView, View, Text, Image, Input } from '@tarojs/components';
import React, { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { connect } from 'react-redux';
import './index.less';
import * as T from './types';
import actions from './actions';
import { store2Props } from './selectors';
import searchImg from '@/assets/image/index/g_search.png'
import trashImg from '@/assets/image/index/trash.png'

actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  textInput: any;
  constructor(props) {
    super(props);
    this.state = {
      cueNow: 1,
      searchValue: '',
      //本地查询的搜索历史记录
      searchHistory: [],
      //是否显示搜索信息
      isShowRes: false,
      autoFocus: false,
    };
  }

  componentDidMount() { }

  componentDidShow() {
    // input聚焦
    this.textInput.focus();
    let searchHistory = Taro.getStorageSync('homeSearchHistory');
    if (searchHistory.length > 0) {
      this.setState({ searchHistory })
    }
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  //点击删除历史记录
  clickDeleteSearchHistory() {
    let that = this;
    Taro.showModal({
      title: '温馨提示',
      content: '确认删除全部历史记录？',
      success: function (res) {
        if (res.confirm) {
          that.setState(
            {
              searchHistory: [],
            },
            () => {
              Taro.removeStorageSync('homeSearchHistory');
            },
          );
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      },
      confirmColor: '#218CFF'
    });
  }

  //添加搜索历史记录
  addSearchHistory() {
    let { searchValue, searchHistory } = this.state;
    if (!searchValue) return;
    if (searchHistory && searchHistory.length > 0) {
      if (searchHistory.indexOf(searchValue) == -1) {
        searchHistory.unshift(searchValue);
        let dd = searchHistory.slice(0, 10);
        this.setState(
          {
            searchHistory: dd,
          },
          () => {
            Taro.setStorageSync('homeSearchHistory', dd)
          },
        );
      }
    } else {
      searchHistory.unshift(searchValue);
      this.setState(
        {
          searchHistory: searchHistory,
        },
        () => {
          Taro.setStorageSync('homeSearchHistory', searchHistory)
        },
      );
    }
  }

  //点击搜索功能
  GoodsSearchClick() {
    let { searchValue, cueNow } = this.state;
    Taro.navigateTo({
      url: `/pages/package-A/search/list/index?searchValue=${searchValue}&cueNow=${cueNow}`
    })
  }

  render() {
    let { searchHistory, autoFocus, searchValue } = this.state;
    return (
      <View className="packageASearch">
        <View className="searchBar">
          <View className="content">
            <Image src={searchImg} className="imgIcon" mode="widthFix"
              onClick={() => {
                this.addSearchHistory();
                this.GoodsSearchClick();
              }} />
            <Input
              className="searchText"
              maxlength={16}
              type="text"
              placeholder="请输入关键字搜索"
              value={searchValue}
              onInput={(e) => {
                let str = ''
                if (e.detail.value) {
                  let zz = e.detail.value.replace(
                    /[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]/g,
                    '',
                  );
                  str = zz.replace(
                    /[`~!@#$%^&*()=+|{}.<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？':;']/g,
                    '',
                  );
                }
                this.setState({
                  searchValue: str,
                });
              }}
              onConfirm={(e) => {
                this.addSearchHistory();
                this.GoodsSearchClick();
              }}
              ref={(input) => { this.textInput = input; }}
            />
          </View>
          <View className="btn"
            onClick={() => {
              Taro.navigateBack();
            }}>
            <Text>取消</Text>
          </View>
        </View>
        <View className="barBox">
          <View
            className="t_view"
            onClick={() => this.setState({ cueNow: 1 })}>
            <Text
              className={this.state.cueNow == 1 ? 't_a_test' : 't_text'}>
              商品
            </Text>
            <View className={this.state.cueNow == 1 ? 't_a_border' : 't_border'}></View>
          </View>
          <View
            className="t_view"
            onClick={() => this.setState({ cueNow: 0 })}>
            <Text
              className={this.state.cueNow == 0 ? 't_a_test' : 't_text'}>
              服务
            </Text>
            <View className={this.state.cueNow == 0 ? 't_a_border' : 't_border'}></View>
          </View>
        </View>
        <View style={{ flex: 1, backgroundColor: '#FFFFFF' }}>
          {searchHistory.length > 0 && (
            <ScrollView scrollY>
              <View className='searchHistory'>
                <View className='r_sb'>
                  <Text className='f36'>
                    搜索历史
                  </Text>
                  <View
                    onClick={() => {
                      this.clickDeleteSearchHistory();
                    }}>
                    <Image src={trashImg} className="imgIcon" mode="widthFix" />
                  </View>
                </View>
                <View className='h_list_box'>
                  {searchHistory.map((item, index) => {
                    return (
                      <View
                        className='h_list_item'
                        onClick={() => {
                          this.setState(
                            {
                              searchValue: item,
                            },
                            () => {
                              this.addSearchHistory();
                              this.GoodsSearchClick();
                            },
                          );
                        }}>
                        <Text className='h_list_text'>
                          {item}
                        </Text>
                      </View>
                    );
                  })}
                </View>
              </View>
            </ScrollView>
          )}
        </View>
      </View>
    );
  }
}
